package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.api.service.IdService;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class VideoApiImpl implements VideoApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKey(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 保存小视频
     *
     * @param video
     * @return 保存成功后，返回视频id
     */
    @Override
    public String saveVideo(Video video) {
        //校验
        if (!ObjectUtil.isAllNotEmpty(video.getUserId(),
                video.getPicUrl(), video.getVideoUrl())) {
            return null;
        }

        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(this.idService.createId(IdType.VIDEO));
        video.setSeeType(1);

        this.mongoTemplate.save(video);

        return video.getId().toHexString();
    }

    /**
     * 查询小视频列表，优先展现推荐的视频，如果没有推荐的视频或已经查询完成，就需要查询系统视频数据
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //从redis中获取推荐视频的数据
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        List<Long> vids = new ArrayList<>();
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(redisData)) {
            //手动分页查询数据
            List<String> vidList = StrUtil.split(redisData, ',');
            //计算分页
            //[0, 10]
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0]; //开始
            int endIndex = Math.min(startEnd[1], vidList.size()); //结束

            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Convert.toLong(vidList.get(i)));
            }
            recommendCount = vidList.size();
        }

        if (CollUtil.isEmpty(vids)) {
            //没有推荐或前面推荐已经查询完毕，查询系统的视频数据

            //计算前面的推荐视频页数
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);

            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize,
                    Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);
            return pageInfo;
        }

        //根据vid查询对应的视频数据了
        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videoList = this.mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);

        return pageInfo;
    }

    @Override
    public Video queryVideoById(String videoId) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(videoId)));
        return this.mongoTemplate.findOne(query, Video.class);
    }

//    @Override
//    public Boolean likeComment(Long userId, String videoId) {
//        //判断是动态id还是评论id
//        Video video = this.queryVideoById(videoId);
//        Comment commentById = this.queryCommentById(videoId);
//        if(ObjectUtil.isNotEmpty(video)) {
//            //判断该用户是否已经点赞
//            if(this.queryUserIsLike(userId, videoId)) {
//                return false;
//            }
//
//            //将数据保存到MongoDB
//            Comment comment = new Comment();
//            comment.setCommentType(CommentType.Like.getType());
//            comment.setCreated(System.currentTimeMillis());
//            comment.setPublishId(new ObjectId(videoId));
//            comment.setIsParent(false);
//            comment.setUserId(userId);
//            //Publish publish = this.queryPublishById(publishId);
//            comment.setPublishUserId(video.getUserId());
//            this.mongoTemplate.save(comment);
//
//            //将点赞数以及用户是否点赞记录到redis中
//            String redisKey = this.getCommentRedisKey(videoId);
//            Object hashKey = CommentType.Like.name();
//            this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
//
//            //标识该用户已经点赞
//            this.redisTemplate.opsForHash().put(redisKey, this.getCommentUserLikeRedisKey(userId), "1");
//
//            return true;
//        } else {
//            //判断该用户是否已经点赞
//            if(this.queryUserIsLike(userId, videoId)) {
//                return false;
//            }
//
//            //将数据保存到MongoDB
//            Comment comment = new Comment();
//            comment.setCommentType(CommentType.Like.getType());//点赞
//            comment.setCreated(System.currentTimeMillis());//点赞日期
//            comment.setPublishId(new ObjectId(videoId));//评论id
//            comment.setIsParent(false);
//            comment.setUserId(userId);//点赞人id
//            //Publish publish = this.queryPublishById(publishId);
//            comment.setPublishUserId(commentById.getUserId());//设置评论作者id
//            this.mongoTemplate.save(comment);
//
//            //将点赞数以及用户是否点赞记录到redis中
//            String redisKey = this.getCommentRedisKey(videoId);
//            Object hashKey = CommentType.Like.name();
//            this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
//
//            //标识该用户已经点赞
//            this.redisTemplate.opsForHash().put(redisKey, this.getCommentUserLikeRedisKey(userId), "1");
//
//            return true;
//        }
//    }

    @Override
    public Comment queryCommentById(String commentId) {
        Query query = Query.query(Criteria.where("_id").is(new ObjectId(commentId))
                .and("commentType").is(CommentType.COMMENT.getType()));
        Comment comment = this.mongoTemplate.findOne(query, Comment.class);
        return comment;
    }

//    @Override
//    public Boolean disLikeComment(Long userId, String videoId) {
//        if(!this.queryUserIsLike(userId, videoId)) {
//            return false;
//        }
//
//        //删除mongodb中的记录
//        Query query = Query.query(Criteria.where("userId").is(userId)
//                .and("publishId").is(new ObjectId(videoId))
//                .and("commentType").is(CommentType.Like.getType()));
//        this.mongoTemplate.remove(query, Comment.class);
//
//        //修改redis中的数据
//        String redisKey = getCommentRedisKey(videoId);
//        Object hashKey = CommentType.Like.name();
//        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
//
//        //删除已点赞的标志
//        this.redisTemplate.opsForHash().delete(redisKey, this.getCommentUserLikeRedisKey(userId));
//        return true;
//    }

    @Override
    public Long queryLikeCount(String videoId) {
        String redisKey = this.getCommentRedisKey(videoId);
        String hashKey = CommentType.Like.name();
        return Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey), 0L);
    }

    @Override
    public Boolean queryUserIsLike(Long userId, String videoId) {
        String redisKey = this.getCommentRedisKey(videoId);
        String hashKey = this.getCommentUserLikeRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

//    @Override
//    public Boolean saveComment(Long userId, String videoId, String content) {
//
//        Comment comment = new Comment();
//        comment.setCommentType(CommentType.COMMENT.getType());
//        comment.setContent(content);
//        comment.setCreated(System.currentTimeMillis());
//        //comment.setId(ObjectId.get());
//        Video video = this.queryVideoById(videoId);
//        comment.setPublishUserId(video.getUserId());
//        comment.setUserId(userId);
//        comment.setIsParent(false);
//        comment.setPublishId(new ObjectId(videoId));
//
//        try {
//            this.mongoTemplate.save(comment);
////            Publish publish1 = BeanUtil.toBeanIgnoreError(comment, Publish.class);
////            mongoTemplate.save(publish1);
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;
//    }

    @Override
    public Integer queryCommentCount(ObjectId videoId) {
        Query query = Query.query(Criteria.where("publishId").is(videoId)
                .and("commentType").is(CommentType.COMMENT.getType()));
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);

        return comments.size();
    }

    @Override
    public Boolean queryUserIsFocus(Long userId, Long likeUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId));
        UserLike userLike = this.mongoTemplate.findOne(query, UserLike.class);
        if(ObjectUtil.isEmpty(userLike)) {
            return false;
        }
        return true;
    }

//    @Override
//    public PageInfo<Comment> queryCommentList(String videoId, Integer page, Integer pageSize) {
//        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
//
//        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(videoId))
//                .and("commentType").is(CommentType.COMMENT.getType()))
//                .with(pageRequest);
//        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);
//
//        PageInfo<Comment> pageInfo = new PageInfo<>();
//        pageInfo.setTotal(comments.size());
//        pageInfo.setPageNum(page);
//        pageInfo.setPageSize(pageSize);
//        pageInfo.setRecords(comments);
//
//        return pageInfo;
//    }

    @Override
    public Boolean userFocus(String userId, String focusId) {
        try {
            UserLike userLike = new UserLike();
            userLike.setUserId(Convert.toLong(userId));
            userLike.setLikeUserId(Convert.toLong(focusId));
            userLike.setId(ObjectId.get());
            userLike.setCreated(System.currentTimeMillis());

            this.mongoTemplate.save(userLike);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Object userUnFocus(String userId, String uid) {
        Query query = Query.query(Criteria.where("userId").is(Convert.toLong(userId))
                .and("likeUserId").is(Convert.toLong(uid)));
        this.mongoTemplate.remove(query, UserLike.class);
        return null;
    }
}
